import time
import threading
from datetime import datetime
from main import HybridLogisticsSystem

# 全局日志文件
log_file = None

def log_print(message):
    """打印到终端并写入文件"""
    # print(message)
    if log_file:
        log_file.write(message + '\n')
        log_file.flush()

def monitor_hybrid_system(system: HybridLogisticsSystem, duration: int):
    """监控混合系统运行"""
    start_time = time.time()
    
    while time.time() - start_time < duration:
        stats = system.get_system_stats()
        
        log_print(f"\n=== 混合智能体-流水线系统状态 (运行时间: {stats['runtime_seconds']:.1f}s) ===")
        log_print(f"总包裹数: {stats['total_packages']}")
        log_print(f"完成包裹: {stats['completed_packages']}")
        log_print(f"异常包裹: {stats['exception_packages']}")
        log_print(f"活跃智能体: {stats['active_package_agents']}")
        log_print(f"吞吐量: {stats['throughput_per_minute']:.2f} 包裹/分钟")
        
        log_print("\n智能阶段状态:")
        for stage_name, stage_stats in stats['stages'].items():
            log_print(f"  {stage_stats['name']}:")
            log_print(f"    已处理: {stage_stats['processed_count']}")
            log_print(f"    输入队列: {stage_stats['input_queue_size']}")
            log_print(f"    输出队列: {stage_stats['output_queue_size']}")
            log_print(f"    工作线程: {stage_stats['workers']}")
            log_print(f"    负载因子: {stage_stats['load_factor']:.2f}")
            log_print(f"    平均处理时间: {stage_stats['avg_processing_time']:.2f}s")
            log_print(f"    注册智能体: {stage_stats['registered_agents']}")
        
        time.sleep(2.5)

def simulate_continuous_orders(system: HybridLogisticsSystem, duration: int):
    """模拟持续下单"""
    start_time = time.time()
    order_count = 0
    
    while time.time() - start_time < duration:
        order_count += 1
        
        # 模拟不同优先级的订单 - 智能体系统处理
        if order_count % 15 == 0:
            priority = 3  # 特急
        elif order_count % 6 == 0:
            priority = 2  # 加急
        else:
            priority = 1  # 普通
        
        system.add_package(
            tracking_id=f"HYBRID{order_count:04d}",
            sender=f"智能商家{order_count % 6 + 1}",
            receiver=f"智能用户{order_count}",
            location=f"智能城市{order_count % 4 + 1}",
            priority=priority
        )
        
        # 智能体-流水线混合系统高效处理
        time.sleep(0.25)

def main():
    """混合智能体-流水线物流系统演示"""
    global log_file
    
    # 创建日志文件
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_filename = f"delivery_sys_log_{timestamp}.txt"
    log_file = open(log_filename, 'w', encoding='utf-8')
    
    try:
        log_print("=== 物流管理系统演示 ===\n")
        log_print(f"日志文件: {log_filename}\n")
        
        # 创建并启动混合系统
        system = HybridLogisticsSystem()
        system.start()
        
        log_print("物流管理系统已启动，开始演示...\n")
        
        # 1. 批量初始订单 - 测试混合系统处理能力
        log_print("1. 添加初始批量订单...")
        initial_orders = [
            {'tracking_id': f'INIT{i:03d}', 'sender': f'发货商{i%4+1}', 
             'receiver': f'收货人{i}', 'location': f'起始城市{i%3+1}', 
             'priority': 3 if i % 10 == 0 else (2 if i % 5 == 0 else 1)}
            for i in range(18)
        ]
        system.batch_add_packages(initial_orders)
        
        # 2. 启动持续订单模拟
        log_print("2. 启动持续订单模拟...")
        order_thread = threading.Thread(
            target=simulate_continuous_orders, 
            args=(system, 22)
        )
        order_thread.daemon = True
        order_thread.start()
        
        # 3. 监控混合系统运行
        log_print("3. 开始监控系统运行...\n")
        monitor_hybrid_system(system, 22)
        
        # 4. 混合系统最终统计
        log_print("\n=== 系统最终统计 ===")
        final_stats = system.get_system_stats()
        
        log_print(f"系统运行时间: {final_stats['runtime_seconds']:.2f}s")
        log_print(f"总处理包裹: {final_stats['total_packages']}")
        log_print(f"成功完成: {final_stats['completed_packages']}")
        log_print(f"活跃智能体: {final_stats['active_package_agents']}")
        log_print(f"异常处理: {final_stats['exception_packages']}")
        log_print(f"平均吞吐量: {final_stats['throughput_per_minute']:.2f} 包裹/分钟")
        
        # 计算系统效率
        completion_rate = (final_stats['completed_packages'] / final_stats['total_packages'] * 100) if final_stats['total_packages'] > 0 else 0
        log_print(f"完成率: {completion_rate:.1f}%")
        
        log_print("\n智能阶段性能分析:")
        for stage_name, stage_stats in final_stats['stages'].items():
            efficiency = stage_stats['processed_count'] / (final_stats['runtime_seconds'] / 60) if final_stats['runtime_seconds'] > 0 else 0
            log_print(f"  {stage_stats['name']}:")
            log_print(f"    处理效率: {efficiency:.2f} 包裹/分钟")
            log_print(f"    平均负载: {stage_stats['load_factor']:.2f}")
            log_print(f"    智能体管理: {stage_stats['registered_agents']} 个")
            log_print(f"    处理质量: {stage_stats['avg_processing_time']:.2f}s 平均时间")
        
        # 性能对比建议
        log_print("\n=== 系统性能建议 ===")
        if final_stats['throughput_per_minute'] > 15:
            log_print("✅ 系统吞吐量优秀，混合架构效果显著")
        elif final_stats['throughput_per_minute'] > 10:
            log_print("✅ 系统吞吐量良好，可考虑增加工作线程")
        else:
            log_print("⚠️ 系统吞吐量需要优化，建议调整参数")
    
    finally:
        # 清理资源
        log_print("\n正在停止混合系统...")
        system.stop()
        log_print("物流管理系统已停止")
        
        # 关闭日志文件
        if log_file:
            log_file.close()
            print(f"\n日志已保存到: {log_filename}")

if __name__ == "__main__":
    main()